package com.cx.mall.goods.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cx.mall.common.model.goods.*;
import com.cx.mall.common.utils.ResponseEnum;
import com.cx.mall.goods.mapper.SkuInfoMapper;
import com.cx.mall.goods.mapper.SpuSaleAttrMapper;
import com.cx.mall.goods.mapper.SpuSaleAttrValueMapper;
import com.cx.mall.goods.service.ICategoryService;
import com.cx.mall.goods.service.ISkuInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cx.mall.goods.service.ISpuInfoService;
import com.cx.mall.goods.service.ISpuSaleAttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author lyt
 * @since 2025-07-10
 */
@Service
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoMapper, SkuInfo> implements ISkuInfoService {

    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private ISpuInfoService spuInfoService;
    @Autowired
    private ISpuSaleAttrService spuSaleAttrService;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Override
    public Page page(Product product) {
        //1、构建条件构造器
        LambdaQueryChainWrapper<SkuInfo> wrapper = new LambdaQueryChainWrapper<>(baseMapper);
        //2、填充条件
        //2.1、按三级类别id查询
        if (product.getCategoryId() != null) {
            wrapper.eq(SkuInfo::getCategoryId, product.getCategoryId());
        }
        //2.2、按二级类别id查询
        if (product.getTwoCategoryId() != null) {
            List<Integer> threeIds = categoryService.listByParentId(product.getTwoCategoryId());
            wrapper.in(SkuInfo::getCategoryId, threeIds);
        }
        //2.3、按一级类别id查询
        if (product.getOneCategoryId() != null) {
            List<Integer> twoIds = categoryService.listByParentId(product.getOneCategoryId());
            List<Integer> threeIds = categoryService.listByParentId(twoIds);
            wrapper.in(SkuInfo::getCategoryId, threeIds);
        }
        //2.4、按品牌id查询
        if (product.getBrandId() != null) {
            wrapper.eq(SkuInfo::getBrandId, product.getBrandId());
        }
        //2.5、按名称查询
        if (product.getSkuName() != null) {
            wrapper.like(SkuInfo::getSkuName, product.getSkuName());
        }
        //2.6、筛选列
        wrapper.select(SkuInfo::getId, SkuInfo::getSpuId, SkuInfo::getSkuName, SkuInfo::getPrice, SkuInfo::getSkuDefaultImg);
        //分页
        //3.1、创建分页对象
        Page page = new Page();
        //3.2设置当前页码
        if (product.getCurrent() != null) {
            page.setCurrent(product.getCurrent());
        }
        //3.3设置每页大小
        if (product.getSize() != null) {
            page.setSize(product.getSize());
        }
        return wrapper.page(page);
    }

    /**
     * 减库存
     *
     * @param stocks
     */
//    @Override
//    public void decreaseStock(List<Stock> stocks) {
//        //保存需要递减的商品
//        List<SkuInfo> skuInfos = new ArrayList<>();
////        List<SkuInfo> list = baseMapper.selectBatchIds(stocks);
//        for (Stock stock: stocks) {
//            //查询商品的数量
//            SkuInfo skuInfo = baseMapper.selectById(stock.getSkuId());
//            //商品不存在或者数量小于购买数量,抛出异常
//            if(skuInfo ==  null || skuInfo.getNum() < stock.getQuantity()){
//                throw new RuntimeException(ResponseEnum.STOCK_NOT_ENOUGH.getMessage());
//            }
//            //库存减少
//            SkuInfo newSkuInfo = new SkuInfo();
//            newSkuInfo.setId(skuInfo.getId());
//            newSkuInfo.setNum(skuInfo.getNum() - stock.getQuantity());
//            //保存商品
//            skuInfos.add(newSkuInfo);
//        }
//        //更新商品
//        baseMapper.updateById(skuInfos);
//    }
    @Transactional
    @Override
    public void decreaseStock(List<Stock> stocks) {
        // 提取所有商品id
        List<String> skuIds = stocks.stream()
                .map(Stock::getSkuId)
                .collect(Collectors.toList());
        // 批量查询商品信息
        List<SkuInfo> skuInfoList = baseMapper.selectBatchIds(skuIds);

        Map<String, SkuInfo> skuInfoMap = skuInfoList.stream()
                .collect(Collectors.toMap(sku -> String.valueOf(sku.getId()), skuInfo -> skuInfo));

        // 保存需要递减的商品
        List<SkuInfo> skuInfos = new ArrayList<>();

        for (Stock stock : stocks) {
            SkuInfo skuInfo = skuInfoMap.get(stock.getSkuId());

            // 商品不存在或者数量小于购买数量,抛出异常
            if (skuInfo == null || skuInfo.getNum() < stock.getQuantity()) {
                throw new RuntimeException(ResponseEnum.STOCK_NOT_ENOUGH.getMessage());
            }
            // 减少库存
            SkuInfo updateSkuInfo = new SkuInfo();
            updateSkuInfo.setId(skuInfo.getId());
            updateSkuInfo.setNum(skuInfo.getNum() - stock.getQuantity());
            skuInfos.add(updateSkuInfo);
        }
        // 批量更新商品库存
        updateBatchById(skuInfos);
    }

    @Override
    public String queryByUserIdAndSkuId(String userId, String skuId) {
        System.out.println("读取数据");
        return skuId;
    }

    @Override
    public ProductDetailDTO queryById(Long id) {
        ProductDetailDTO spuInfoDTO = new ProductDetailDTO();
        // 获取Spu
        SpuInfo spuInfo = spuInfoService.getById(id);
        if(spuInfo != null){
            // 获取spu类别
            List<String> categoryNames = categoryService.getCategoryNames(spuInfo.getCategoryId());
            // 获取类别的spu销售属性
            Map<String,List<String>> attrMap = spuSaleAttrService.getSpuSaleAttrs(id);
            // 获取商品SKU信息
            List<SkuInfo> skuInfoList = listSkuInfo(id);
            // 封装数据
            spuInfoDTO = new ProductDetailDTO(categoryNames,attrMap,skuInfoList);
        }
        return spuInfoDTO;
    }



    /**
     * 获取SPU的SKU集合
     */
    public List<SkuInfo> listSkuInfo(Long spuId){
        LambdaQueryChainWrapper<SkuInfo> wrapper = new LambdaQueryChainWrapper<>(baseMapper);
        wrapper.eq(SkuInfo::getSpuId,spuId);
        return wrapper.list();
    }


}
